﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility.Grid;
using ConfExpert.Utility.Peripheral;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using DevTeamIT;
using Extensions;
using ITaskManager.Datasets;
using ITaskManager.Datasets.MyDataTableAdapters;
using ITaskManager.Forms;
using ITaskManager.Forms.IT;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.IT
{
    /*
        DetailView yerine yeni form
        hücreye sağ tık (Taranmış belgeyi göster)
        pdf saklama
    */

    public partial class Fatura : XForm
    {
        public Fatura()
        {
            InitializeComponent();
        }

        BindingSource bs1, bs2;

        private void Fatura_Load(object sender, EventArgs e)
        {
            TAM.IT_FaturaTableAdapter = new IT_FaturaTableAdapter();
            TAM.IT_FaturaLinesTableAdapter = new IT_FaturaLinesTableAdapter();
            ds.IT_Fatura.Columns.Add("FaturaTutari", typeof(decimal));
            ds.IT_Fatura.Columns.Add("ToplamTutar", typeof(decimal));
            ds.IT_FaturaLines.Columns.Add("SatirTutari", typeof(decimal));

            SetExpression(true);

            GetDetails("IT_Fatura;IT_FaturaLines", "IT_GetFatura", Session.SirketId, chkGecmisFatura.Checked);
            bs1 = new BindingSource(ds, "IT_Fatura");
            bs2 = new BindingSource(bs1, "FK_IT_FaturaLines_IT_Fatura_IT_FaturaId");
            AddBsToList(bs1, bs2);

            InitGridView(gvFatura, bs1);
            InitGridView(gvFaturaLines, bs2);
            
            ds.IT_Fatura.TableNewRow += IT_Fatura_TableNewRow;
            gvFatura.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gvFaturaLines.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;


            GridColumn colUrun = gvFaturaLines.Columns["UrunAdi"];
            colUrun.ColumnEdit = GetIntellisensedRI(ExecuteDataTable("GetDistinctValues", "UrunAdi"));
            ((RepositoryItemGridLookUpEdit)colUrun.ColumnEdit).ProcessNewValue += ri_NewValue;

            gvFatura.MakeEditable("DosyaId", "IT_FaturaId");
            gvFatura.FormatAsNumber(2, "FaturaTutari", "ToplamTutar");
            gvFatura.AddSummary("FaturaTutari", "ToplamTutar");
            gvFatura.YanYanaGetir("FaturaTutari:Iskonto");
            gvFatura.MakeColumnInvisible("InsertedOn", "IT_FaturaId");
            gvFatura.SetCaptions("Aciklama:Açıklama", "KDVOrani:KDV %", "FaturaTutari:Fatura Tutarı", "DosyaId:Evrak");
            gvFatura.RowCellClick += gvFatura_RowCellClick;
            gvFatura.CustomDrawCell += gvFatura_CustomDrawCell;

            GridMenu gm = GridManager.GetManager(gvFatura).GridMenu;
            gm.AddMenu("Evrak Ekle/Güncelle", EvrakEkle);

            gvFaturaLines.MakeColumnInvisible("IT_FaturaId", "IT_FaturaLinesId", "InsertedOn");
            gvFaturaLines.SetCaptions("UrunAdi:Ürün", "KullanimAmaci:Kullanım Amacı", "SatirTutari:Satır Tutarı");
            gvFaturaLines.FormatAsNumber(2, "BirimFiyat", "SatirTutari");

            //GridManager gm = GridManager.GetManager(gvFaturaLines);
            //gm.GridMenu.AddMenu("Envanter Kaydı", EnvanterBilgi_Click);

            splitter.AutoSize();
            btnKaydet.ItemClick += btnKaydet_ItemClick;
            gvFatura.FocusedRowChanged += gvFatura_FocusedRowChanged;
            btnTara.ItemClick += btnTara_ItemClick;
            chkGecmisFatura.CheckedChanged += chkGecmisFatura_CheckedChanged;
            FormClosing += Fatura_FormClosing;
            gvFaturaLines.DoubleClick += gvFaturaLines_DoubleClick;

            gvFatura.MoveLast();

            LongestUrunAdi = CalcLongestUrunAdi();
            BestFit();
        }

        void gvFaturaLines_DoubleClick(object sender, EventArgs e)
        {
            FaturaLinesDuzenle(gvFaturaLines);
        }

        private void FaturaLinesDuzenle(GridView gvFaturaLines)
        {
            if (gvFaturaLines.GetFocusedDataRow() != null)
            {
                int IT_FaturaLinesId = (int)gvFaturaLines.GetFocusedDataRow()["IT_FaturaLinesId"];

                if (IT_FaturaLinesId > 0)
                {
                    using (FaturaLinesDuzenle fDuzenle = new FaturaLinesDuzenle(IT_FaturaLinesId))
                        fDuzenle.ShowDialog();

                    GetDetails("IT_Fatura;IT_FaturaLines", "IT_GetFatura", Session.SirketId, chkGecmisFatura.Checked);
                    BestFit();
                }
            }
        }
        int LongestUrunAdi = 0;

        int CalcLongestUrunAdi()
        {
            int MaxSize = 0;
            Graphics gr = Graphics.FromHwnd(gvFaturaLines.GridControl.Handle);
            DataTable dt = (DataTable)((RepositoryItemGridLookUpEdit)gvFaturaLines.Columns["UrunAdi"].ColumnEdit).DataSource;

            foreach (DataRow r in dt.Rows)
            {
                SizeF size = gr.MeasureString(r["Name"].ToString(), gvFaturaLines.PaintAppearance.Row.GetFont());
                if (size.Width > MaxSize)
                    MaxSize = size.Width.ToInt();
            }

            return MaxSize;
        }

        void gvFatura_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            if (e.Column.FieldName == "DosyaId")
            {
                bool found = e.CellValue.ToInt() > 0;
                if (found)
                {
                    e.DisplayText = "var";
                    e.Appearance.FontStyleDelta = FontStyle.Underline;
                    e.Appearance.ForeColor = Color.Blue;
                    e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                }

            }
        }

        void gvFatura_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "DosyaId")
            {
                int dosyaId = e.CellValue.ToInt();
                if (dosyaId > 0)
                {
                    Cursor.Current = Cursors.WaitCursor;

                    DataRow dr = ExecuteDataTable("Files.dbo.GetDosya", dosyaId).Rows[0];
                    int tip = 0;

                    if (dr["DosyaAdi"].ToStr().Contains("PDF"))
                        tip = 1;

                    using (ImageViewer iv = new ImageViewer((byte[])dr["Blob"], tip))
                        iv.ShowDialog();

                    GC.Collect();

                    Cursor.Current = Cursors.Default;
                }
            }
        }

        private void EvrakEkle(object sender, EventArgs e)
        {
            try
            {
                int faturaId = gvFatura.GetFocusedDataRow()["IT_FaturaId"].ToInt();
                if (faturaId > 0)
                {
                    gvFatura.EndEdit();
                    gvFaturaLines.EndEdit();

                    OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Filter = "JPG|*.jpg|PDF|*.pdf";

                    int dosyaId = gvFatura.GetFocusedRowCellValue("DosyaId").ToInt();
                    if (dosyaId > 0)
                    {
                        if (XtraMessageBox.Show("Mevcut evrağı değiştireceksiniz ! Emin misiniz?", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                            return;
                    }

                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        FileInfo fi = new FileInfo(ofd.FileName);
                        if (!".PDF .JPG".Contains(fi.Extension.ToUpper()))
                        {
                            ShowErrorMessage("PDF ya da JPG seçmelisiniz!");
                            return;
                        }

                        byte[] file = File.ReadAllBytes(ofd.FileName);

                        if (dosyaId < 0)
                        {
                            int yeniDosyaId = ExecuteScalar("files.dbo.InsDosya", faturaId.ToStr() + fi.Extension.ToUpper(), file, 6).ToInt();
                            gvFatura.SetFocusedRowCellValue("DosyaId", yeniDosyaId);
                            XtraMessageBox.Show("Evrak eklendi.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            ExecuteScalar("files.dbo.UpdDosya", dosyaId, faturaId.ToStr() + fi.Extension.ToUpper(), file).ToInt();
                            XtraMessageBox.Show("Evrak güncellendi.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }



                        //btnKaydet.PerformClick();

                        //this.Cursor = Cursors.WaitCursor;

                        ////Scanner scanner = new Scanner();
                        //Image i2 = Scanner.ScanDoc();    //kumaş için sabitlendi

                        //if (i2 != null)
                        //{
                        //    int IT_FaturaId = gvFatura.GetFocusedDataRow()["IT_FaturaId"].ToInt();

                        //    ds.xBuffer.Clear();

                        //    MyData.xBufferRow xpr = ds.xBuffer.NewxBufferRow();
                        //    xpr.intVal = IT_FaturaId;
                        //    xpr.photoVal = ConvertImageToByteArray(i2, System.Drawing.Imaging.ImageFormat.Png);
                        //    ds.xBuffer.AddxBufferRow(xpr);

                        //    ExecQueryTV("UpdxBuffer", ds.xBuffer, 6);
                        //    GC.Collect();
                        //    Notify("Kaydedildi");

                        //    //gvRoll.Columns["Photo"].Width = 34;
                        //}
                    }
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        void chkGecmisFatura_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            ds.IT_FaturaLines.Clear();
            ds.IT_Fatura.Clear();
            GetDetails("IT_Fatura;IT_FaturaLines", "IT_GetFatura", Session.SirketId, chkGecmisFatura.Checked);
            BestFit();
        }

        void gvFatura_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            BestFit(false);
        }

        void IT_Fatura_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["Tarih"] = DateTime.Now;
        }

        private void SetExpression(bool set)
        {
            if (set)
            {
                ds.IT_FaturaLines.Columns["SatirTutari"].Expression = "Adet * BirimFiyat";
                ds.IT_Fatura.Columns["FaturaTutari"].Expression = "SUM(Child.SatirTutari)";
                ds.IT_Fatura.Columns["ToplamTutar"].Expression = "(FaturaTutari - ISNULL(Iskonto,0))* (1+(KDVOrani/100.0))";

            }
            else
            {
                ds.IT_FaturaLines.Columns["SatirTutari"].Expression = null;
                ds.IT_Fatura.Columns["ToplamTutar"].Expression = null;
                ds.IT_Fatura.Columns["FaturaTutari"].Expression = null;
            }
        }

        void btnKaydet_ItemClick(object sender, ItemClickEventArgs e)
        {
            gvFatura.EndEdit();
            gvFaturaLines.EndEdit();

            SetExpression(false);

            Save();

            SetExpression(true);
            BestFit();
        }

        private void BestFit(bool parenttable = true)
        {
            if (parenttable)
                gvFatura.BestFitColumns();

            gvFaturaLines.BestFitColumns();
            gvFaturaLines.Columns["UrunAdi"].Width = LongestUrunAdi;
        }

        private void Fatura_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ds.IT_Fatura.HasChanged() || ds.IT_FaturaLines.HasChanged())
            {
                DialogResult dr = MessageBox.Show("Yaptığınız değişiklikleri kaydetmediniz!\r\n\r\nÇıkmak istediğinize emin misiniz?", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (dr == DialogResult.No)
                    e.Cancel = true;
                else
                    e.Cancel = false;
            }
        }

        void btnTara_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                gvFatura.EndEdit();
                gvFaturaLines.EndEdit();
                btnKaydet.PerformClick();

                this.Cursor = Cursors.WaitCursor;

                //Scanner scanner = new Scanner();
                Image i2 = Scanner.ScanDoc();    //kumaş için sabitlendi

                if (i2 != null)
                {
                    int IT_FaturaId = gvFatura.GetFocusedDataRow()["IT_FaturaId"].ToInt();

                    ds.xBuffer.Clear();

                    MyData.xBufferRow xpr = ds.xBuffer.NewxBufferRow();
                    xpr.intVal = IT_FaturaId;
                    xpr.photoVal = ConvertImageToByteArray(i2, System.Drawing.Imaging.ImageFormat.Png);
                    ds.xBuffer.AddxBufferRow(xpr);

                    ExecQueryTV("UpdxBuffer", ds.xBuffer, 6);
                    GC.Collect();
                    Notify("Kaydedildi");

                    //gvRoll.Columns["Photo"].Width = 34;
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }



        void ExecQueryTV(string SP, params object[] p)
        {
            using (SqlConnection sqlConn = new SqlConnection(Session.DataManager.ConnectionString))
            {
                sqlConn.Open();
                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.CommandText = SP;
                sqlCmd.CommandType = CommandType.StoredProcedure;
                SqlParameter[] parameters = new SqlParameter[2];
                parameters[0] = new SqlParameter("@tbl", SqlDbType.Structured);
                parameters[0].Value = p[0];
                parameters[1] = new SqlParameter("@TurId", SqlDbType.Int);
                parameters[1].Value = p[1];
                sqlCmd.Parameters.AddRange(parameters);
                sqlCmd.ExecuteNonQuery();
            }
        }

        public object[] UrunAdi { get; set; }

        public object KullanimAmaci { get; set; }

        public object Adet { get; set; }

        public object BirimFiyat { get; set; }
    }
}
